package com.example.ximalayademo.views;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;

import androidx.annotation.Nullable;

import com.example.ximalayademo.R;

public class LoadingView extends androidx.appcompat.widget.AppCompatImageView {

    //旋转角度
    private int rotateDegree = 0;

    private boolean mNeedRotate = true;

    public LoadingView(Context context) {
        this(context , null);  //设置this   为了不管哪个方法进来，都执行第三个方法
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs , 0);
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //设置图标
        setImageResource(R.mipmap.loading);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        //绑定到view时
        post(new Runnable() {
            @Override
            public void run() {
                rotateDegree += 30;
                rotateDegree = rotateDegree > 360 ? 0 : rotateDegree;
                invalidate();
                if (mNeedRotate) {
                    postDelayed(this , 100);
                }
            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        //解除绑定
        mNeedRotate = false;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        /**
         * 第一个 ： 旋转角度  第二个： 宽  第三个：高
         */
        canvas.rotate( rotateDegree,  getWidth()/2 , getHeight()/2);
        super.onDraw(canvas);
    }
}
